/*
============================================================================
 Name        : dd_zip.c
 Author      : Jian
 Version     :
 Copyright   : GPL
 Description : dd_zip.c - source file
============================================================================
*/

/* INCLUDE FILES */
#include "dd_zip.h"
#include "dd_log.h"


dd_zip* dd_zip_create() 
{
    dd_zip* zip = dd_malloc(sizeof(dd_zip)) ;
    __DD_CHECK_MEM(zip, sizeof(dd_zip), return NULL) ;
    dd_zip_reset(zip) ;
    return zip ;
}

void dd_zip_destroy(dd_zip* zip) 
{
    __DD_ASSERT_DEFENSE(zip, return) ;

    dd_zip_reset(zip) ;
    dd_free(zip) ;
}

int dd_zip_reset(dd_zip* zip) 
{
    int ret = -1 ;

    __DD_ASSERT_DEFENSE(zip, return -1) ;

    inflateEnd(&zip->zlibStream);

    zip->zlibStream.zalloc   = Z_NULL;
    zip->zlibStream.zfree    = Z_NULL;
    zip->zlibStream.opaque   = Z_NULL;
    zip->zlibStream.next_in  = Z_NULL;

    if((ret = inflateInit2(&zip->zlibStream, 47)) != Z_OK) 
        dd_log_error("dd_zip_reset inflateInit2 got error: %d",ret);

    return ret ;
}

int dd_zip_ungzip(dd_zip* zip, const char* src, int* srcLen, char* dest, int* destLen) 
{
    int ret  = -1;

    __DD_ASSERT_DEFENSE(zip && src && srcLen && dest && destLen, return -1) ;

    zip->zlibStream.next_in   = (DD_BYTE*)src;
    zip->zlibStream.avail_in  = *srcLen;

    zip->zlibStream.next_out  = (DD_BYTE*)dest;
    zip->zlibStream.avail_out = *destLen;

    ret = inflate(&zip->zlibStream, Z_NO_FLUSH);

    if (ret == Z_NEED_DICT || ret < Z_OK) {
        dd_log_error("dd_zip_ungzip inflate got error: %d",ret);
        return -1 ;
    }
    
    *srcLen  = zip->zlibStream.avail_in ;
    *destLen = *destLen - zip->zlibStream.avail_out ;
    return 0 ;
}

/* End of File */
